package org.xserver.token;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xserver.common.util.StringUtil;
import org.xserver.component.core.XServerHttpContextAttachment;
import org.xserver.component.core.XServerHttpRequest;
import org.xserver.component.exception.FilterProcessError;
import org.xserver.component.exception.TokenFilterError;
import org.xserver.component.extension.filter.AbstractContextFilter;
import org.xserver.component.redis.RedisTemplate;
import org.xserver.component.redis.util.RedisConstant;



/**
 * Created by bin on 2016-04-27 11:32.
 *
 * @author bin
 * @version 1.0.0
 * @since 2016-04-27
 */
public class XServerTokenProcessFilter extends AbstractContextFilter {
	private static final Logger log =
			LoggerFactory.getLogger(XServerTokenProcessFilter.class);

	@Resource
	private RedisTemplate redisTemplate;
	@Override
	public void contextInitialized() throws FilterProcessError {

	}

	@Override
	public void contextDestroyed() throws FilterProcessError {

	}

	@Override
	public void process(XServerHttpContextAttachment attachment) throws FilterProcessError {
		XServerHttpRequest xServerHttpRequest = attachment.getRequest();
		String token = (String) xServerHttpRequest.getParameter(("token"));
		if (StringUtil.isEmpty(token)){
			log.error("token is null");
			throw new TokenFilterError(TokenFilterError.TokenFilterErrorEnum.TOKEN_IS_NULL);
		}
		Integer ret = (Integer) redisTemplate.doValidate(token);

		if (ret.intValue() == RedisConstant.TOKEN_ERROE.intValue()){
			log.error(TokenFilterError.TokenFilterErrorEnum.TOKEN_ERROR.getValue());
			throw new TokenFilterError(TokenFilterError.TokenFilterErrorEnum.TOKEN_ERROR);
		}
		else if (ret.intValue() == RedisConstant.TOKEN_OVERDUE.intValue()){
			log.error(TokenFilterError.TokenFilterErrorEnum.TOKEN_ERROR.getValue());
			throw new TokenFilterError(TokenFilterError.TokenFilterErrorEnum.TOKEN_OVERDUE);
		}
		else if (ret.intValue() == RedisConstant.TOKEN_SYSERROR.intValue()){
			log.error(TokenFilterError.TokenFilterErrorEnum.TOKEN_ERROR.getValue());
			throw new TokenFilterError(TokenFilterError.TokenFilterErrorEnum.TOKEN_SYSTEM_ERROR);
		}
		else if (ret.intValue() == RedisConstant.TOKEN_SUCCESS.intValue()){

		}
	}
}
